﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.LightSwitch;

namespace LightSwitchApplication.UserCode
{
    public static class Uti
    {
        public static bool IsNull(object Object)
        {
            if (Object == null)
                return true;
            return false;
        }

        public static object IsNull(object Object, object DefaultObj)
        {
            if (IsNull(Object))
                return DefaultObj;
            return Object;
        }

        public static string GetAutoNumber(DataWorkspace dtw, string Module)
        {
            var auto = dtw.LSWData.SystemAutoNumbers.Where(o => o.ModuleID == Module).Execute();

            SystemAutoNumber autoitem;
            SystemAutoNumberDetail autodetail;
            if (auto.Count() == 0)
            {
                autoitem = dtw.LSWData.SystemAutoNumbers.AddNew();
                autoitem.ModuleID = Module;
                autoitem.Prefix = Module;
            }
            else
            {
                autoitem = auto.ElementAt(0);
            }

            string YYYYMM;
            if (DateTime.Now.Month.ToString().Length == 1)
                YYYYMM = DateTime.Now.Year.ToString() + "0" + DateTime.Now.Month.ToString();
            else
                YYYYMM = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString();

            var autod = dtw.LSWData.SystemAutoNumberDetails.Where(o => o.ModuleID == Module && o.YYYYMM == YYYYMM).Execute();
            if (autod.Count() == 0)
            {
                autodetail = dtw.LSWData.SystemAutoNumberDetails.AddNew();
                autodetail.ModuleID = Module;
                autodetail.Number = 1;
                autodetail.YYYYMM = YYYYMM;
                autodetail.SystemAutoNumber = autoitem;
            }
            else
            {
                autodetail = autod.ElementAt(0);
                autodetail.Number += 1;
            }

            string number = "00000" + autodetail.Number.ToString();
            return autoitem.Prefix + autodetail.YYYYMM + number.Substring(number.Length - 4, 4);
        }
    }
}
